import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  RefreshControl,
  ScrollView,
  StyleSheet,
  Text,
  View,
  Pressable,
  useWindowDimensions,
} from 'react-native';
import { Link, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';

import { useAuth } from '@/context/auth-context';
import { apiRequest, ApiError } from '@/utils/api';

type MerchantSummary = {
  total_orders: number;
  completed_orders: number;
  pending_orders: number;
  canceled_orders: number;
  total_revenue: number;
};

type MerchantTopProduct = {
  product_id: number;
  title: string;
  cover_image: string;
  orders_count: number;
  units_sold: number;
  total_revenue: number;
};

type MerchantRecentOrder = {
  id: number;
  order_number: string;
  customer: string;
  contact: string | null;
  status: string;
  total_amount: number;
  created_at: string;
};

type MerchantTopCustomer = {
  user_id: number;
  username?: string;
  display_name?: string;
  total_spent: number;
  orders_count: number;
};

type MerchantOverviewResponse = {
  summary: MerchantSummary;
  top_products: MerchantTopProduct[];
  recent_orders: MerchantRecentOrder[];
  top_customers?: MerchantTopCustomer[];
};

const palette = {
  background: '#fff7fb',
  surface: '#ffffff',
  accent: '#ff8fb1',
  accentDeep: '#ff6a9b',
  textPrimary: '#2f1f2b',
  textMuted: '#6a566a',
  border: 'rgba(214, 106, 138, 0.18)',
  info: 'rgba(126, 108, 255, 0.18)',
  success: 'rgba(79, 177, 122, 0.18)',
};

function formatCurrency(value: number) {
  return `¥${value.toFixed(2)}`;
}

const initialOverview: MerchantOverviewResponse = {
  summary: {
    total_orders: 0,
    completed_orders: 0,
    pending_orders: 0,
    canceled_orders: 0,
    total_revenue: 0,
  },
  top_products: [],
  recent_orders: [],
  top_customers: [],
};

function normalizeOverview(payload: Partial<MerchantOverviewResponse> | null | undefined) {
  if (!payload) {
    return initialOverview;
  }

  const summary = payload.summary ?? initialOverview.summary;
  return {
    summary: {
      total_orders: Number(summary.total_orders ?? 0),
      completed_orders: Number(summary.completed_orders ?? 0),
      pending_orders: Number(summary.pending_orders ?? 0),
      canceled_orders: Number(summary.canceled_orders ?? 0),
      total_revenue: Number(summary.total_revenue ?? 0),
    },
    top_products: Array.isArray(payload.top_products) ? payload.top_products : [],
    recent_orders: Array.isArray(payload.recent_orders) ? payload.recent_orders : [],
    top_customers: Array.isArray(payload.top_customers) ? payload.top_customers : [],
  };
}

export default function MerchantOverviewScreen() {
  const router = useRouter();
  const { merchantToken: token, setViewMode } = useAuth();
  const { width } = useWindowDimensions();
  const [data, setData] = useState<MerchantOverviewResponse>(initialOverview);
  const [isLoading, setLoading] = useState(true);
  const [isRefreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchOverview = useCallback(
    async (refresh: boolean) => {
      if (!token) {
        setError('登录状态无效，请重新登录');
        return;
      }

      if (refresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }

      try {
        const response = await apiRequest<MerchantOverviewResponse>('/merchant/overview', {
          token,
        });
        setData(normalizeOverview(response));
        setError(null);
      } catch (err) {
        if (err instanceof ApiError && err.status === 401) {
          // 商户令牌失效，跳转到商户登录
          router.replace({ pathname: '/(auth)/login', params: { channel: 'merchant', redirect: '/(merchant)/overview' } });
          return;
        }
        const message = err instanceof Error ? err.message : '概览数据加载失败，请稍后重试';
        setError(message);
      } finally {
        if (refresh) {
          setRefreshing(false);
        } else {
          setLoading(false);
        }
      }
    },
    [router, token],
  );

  useEffect(() => {
    fetchOverview(false);
  }, [fetchOverview]);

  const summaryCards = useMemo(() => {
    const summary = data?.summary ?? initialOverview.summary;
    const average =
      summary.completed_orders > 0 ? summary.total_revenue / summary.completed_orders : 0;

    return [
      {
        title: '累计营收',
        value: formatCurrency(summary.total_revenue),
        hint: `成交订单 ${summary.completed_orders} 单`,
        style: styles.cardAccent,
      },
      {
        title: '成交订单数',
        value: summary.completed_orders.toString(),
        hint: `平均客单价 ${formatCurrency(average)}`,
        style: styles.cardInfo,
      },
    ];
  }, [data]);

  const handleRefresh = useCallback(() => {
    fetchOverview(true);
  }, [fetchOverview]);

  if (isLoading) {
    return (
      <View style={styles.centered}>
        <ActivityIndicator size="large" color={palette.accent} />
        <Text style={styles.mutedText}>正在加载经营概览...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.centered}>
        <Text style={styles.errorText}>{error}</Text>
        <Text style={styles.retryText} onPress={() => fetchOverview(false)}>
          刷新重试
        </Text>
      </View>
    );
  }

  const topCustomers = data.top_customers ?? [];
  const isCompact = width < 768;

  return (
    <ScrollView
      style={styles.container}
      contentContainerStyle={[
        styles.content,
        isCompact ? styles.contentCompact : styles.contentRegular,
      ]}
      refreshControl={
        <RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
      }
    >
      <View style={styles.topbar}>
        <Text style={styles.title}>经营概览</Text>
        <Link href="/(tabs)" asChild>
          <Pressable style={styles.switchLink} onPress={() => setViewMode('customer')}>
            <Ionicons name="swap-horizontal" size={16} color={palette.accentDeep} />
            <Text style={styles.switchLinkText}>切换至 C 端</Text>
          </Pressable>
        </Link>
      </View>
      <Text style={styles.subtitle}>实时掌握已支付订单表现与核心消费榜单</Text>

      <View
        style={[
          styles.summaryGrid,
          isCompact ? styles.summaryGridCompact : styles.summaryGridWide,
        ]}
      >
        {summaryCards.map((card) => (
          <View
            key={card.title}
            style={[
              styles.summaryCard,
              card.style,
              isCompact ? styles.summaryCardCompact : styles.summaryCardWide,
            ]}
          >
            <Text style={styles.cardTitle}>{card.title}</Text>
            <Text style={styles.cardValue}>{card.value}</Text>
            <Text style={styles.cardHint}>{card.hint}</Text>
          </View>
        ))}
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>消费总榜</Text>
        <Text style={styles.sectionSubtitle}>消费金额 Top 5（仅统计已支付订单）</Text>
        {topCustomers.length === 0 ? (
          <Text style={styles.emptyText}>暂无消费数据</Text>
        ) : (
          <View style={styles.cardList}>
            {topCustomers.map((customer, index) => {
              const rank = index + 1;
              const name =
                (customer.display_name && customer.display_name.trim()) ||
                (customer.username && customer.username.trim()) ||
                `用户 ${customer.user_id}`;
              return (
                <View key={`${customer.user_id}-${rank}`} style={styles.customerCard}>
                  <View style={styles.customerBadge}>
                    <Text style={styles.customerBadgeText}>{rank}</Text>
                  </View>
                  <View style={styles.customerInfo}>
                    <Text style={styles.customerName}>{name}</Text>
                    <Text style={styles.customerMeta}>
                      成交 {customer.orders_count} 单 · 累计消费 {formatCurrency(customer.total_spent)}
                    </Text>
                  </View>
                </View>
              );
            })}
          </View>
        )}
      </View>

    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: palette.background,
  },
  content: {
    paddingHorizontal: 20,
    paddingVertical: 24,
    gap: 24,
    alignItems: 'stretch',
  },
  contentCompact: {
    width: '100%',
  },
  contentRegular: {
    width: '100%',
    maxWidth: 960,
    alignSelf: 'center',
  },
  centered: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: palette.background,
    gap: 12,
  },
  mutedText: {
    color: palette.textMuted,
    fontSize: 13,
  },
  errorText: {
    color: '#d64f7c',
    fontSize: 14,
    fontWeight: '600',
  },
  retryText: {
    color: palette.accent,
    fontSize: 13,
    fontWeight: '600',
  },
  title: {
    fontSize: 24,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  subtitle: {
    fontSize: 13,
    color: palette.textMuted,
  },
  topbar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  switchLink: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    paddingHorizontal: 6,
    paddingVertical: 4,
  },
  switchLinkText: {
    fontSize: 12,
    color: palette.accentDeep,
    fontWeight: '600',
  },
  summaryGrid: {
    gap: 16,
  },
  summaryGridCompact: {
    flexDirection: 'column',
  },
  summaryGridWide: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  summaryCard: {
    flexGrow: 1,
    borderRadius: 24,
    paddingHorizontal: 18,
    paddingVertical: 20,
    backgroundColor: palette.surface,
    shadowColor: '#f3c8d8',
    shadowOpacity: 0.2,
    shadowRadius: 12,
    shadowOffset: { width: 0, height: 8 },
    elevation: 4,
    minWidth: 240,
  },
  summaryCardCompact: {
    width: '100%',
  },
  summaryCardWide: {
    flexBasis: '30%',
  },
  cardAccent: {
    backgroundColor: 'rgba(255,143,177,0.16)',
  },
  cardInfo: {
    backgroundColor: palette.info,
  },
  cardTitle: {
    fontSize: 13,
    color: palette.textMuted,
  },
  cardValue: {
    fontSize: 22,
    fontWeight: '700',
    color: palette.textPrimary,
    marginTop: 6,
  },
  cardHint: {
    marginTop: 4,
    fontSize: 12,
    color: palette.textMuted,
  },
  section: {
    gap: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  sectionSubtitle: {
    fontSize: 12,
    color: palette.textMuted,
  },
  emptyText: {
    fontSize: 13,
    color: palette.textMuted,
    paddingVertical: 16,
  },
  cardList: {
    gap: 12,
  },
  customerCard: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    borderRadius: 20,
    backgroundColor: palette.surface,
    borderWidth: 1,
    borderColor: palette.border,
    paddingVertical: 14,
    paddingHorizontal: 16,
  },
  customerBadge: {
    width: 32,
    height: 32,
    borderRadius: 16,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(255,143,177,0.18)',
  },
  customerBadgeText: {
    fontSize: 14,
    fontWeight: '700',
    color: palette.accentDeep,
  },
  customerInfo: {
    flex: 1,
    gap: 4,
  },
  customerName: {
    fontSize: 14,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  customerMeta: {
    fontSize: 12,
    color: palette.textMuted,
  },
});
